import { View, Text, Picker, Map, Image } from "@tarojs/components";
import {
  AtList,
  AtListItem,
  AtForm,
  AtInput,
  AtButton,
  AtMessage,
  AtImagePicker
} from "taro-ui";
import { useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import "./index.scss";
import {
  getAreaListApi,
  getProjectAdjustApi,
  getProjectAddApi,
  getAreaApi
} from "../../../utils/api";
import { qtb, btq } from "../../../utils/to";

import { baseUrl } from "../../../utils/http";
import { useSelector, useDispatch } from "react-redux";

const Index = () => {
  const [state, setState] = useState({
    name: "",
    selector: [[], [], []],
    select: [{}, {}, {}],
    comment: "",
    area_code: 0,
    project_code: "",
    address: "",
    building_area: "",
    building_number: "",
    constructor: "",
    constructor_user: "",
    constructor_phone: "",
    builder: "",
    builder_user: "",
    builder_phone: "",
    build_timestamp: ""
  });

  const satellite = useSelector(state => state.yq.satellite);
  const dispatch = useDispatch();

  const [center_latitude, set_center_latitude] = useState("");
  const [center_longitude, set_center_longitude] = useState("");
  const [latitude, set_latitude] = useState("");
  const [longitude, set_longitude] = useState("");

  const [files, set_files] = useState([]);

  const filesChange = files => {
    set_files(files);
  };

  useDidShow(() => {
    getAreaList();
    getAreaApi({
      code: Taro.getStorageSync("code")
    }).then(res => {
      const arr = btq(+res.record.lng, +res.record.lat);
      set_center_latitude(+arr[1]);
      set_center_longitude(+arr[0]);
    });
  });

  // 获取所有区域
  const getAreaList = async () => {
    const res = await getAreaListApi({
      get_count: 1000,
      start_index: 0,
      level: 1
    });
    if (res.res === 0) {
      setState(state => {
        state.selector[0] = res.records;
        return {
          ...state,
          selector: [...state.selector]
        };
      });
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  // 改名称
  const handleChange = (key, value) => {
    setState(state => ({
      ...state,
      [key]: value
    }));
  };

  const onDateChange = e => {
    setState(state => ({
      ...state,
      build_timestamp: e.detail.value
    }));
  };

  const columnChange = async e => {
    if (e.detail.column === 0) {
      setState(state => ({
        ...state,
        select: [state.selector[0][e.detail.value], {}, {}]
      }));

      const res = await getAreaListApi({
        get_count: 1000,
        start_index: 0,
        level: 2,
        parent_code: state.selector[0][e.detail.value].code
      });
      if (res.res === 0) {
        setState(state => {
          state.selector[1] = res.records;
          state.select[1] = res.records[0];
          return {
            ...state,
            selector: [...state.selector]
          };
        });
      } else {
        Taro.atMessage({
          message: res.msg,
          type: "warning"
        });
      }
    } else if (e.detail.column === 1) {
      setState(state => {
        state.select[1] = state.selector[1][e.detail.value];
        return {
          ...state,
          selector: [...state.selector]
        };
      });
      const res = await getAreaListApi({
        get_count: 1000,
        start_index: 0,
        level: 3,
        parent_code: state.selector[1][e.detail.value].code
      });
      if (res.res === 0) {
        setState(state => {
          state.selector[2] = res.records;
          state.select[2] = res.records[0];
          return {
            ...state,
            selector: [...state.selector]
          };
        });
      } else {
        Taro.atMessage({
          message: res.msg,
          type: "warning"
        });
      }
    } else if (e.detail.column === 2) {
      setState(state => {
        state.select[2] = state.selector[2][e.detail.value];
        return {
          ...state,
          area_code: state.select[2].code,
          selector: [...state.selector]
        };
      });
    }
  };

  const mapClick = e => {
    set_latitude(+e.detail.latitude);
    set_longitude(+e.detail.longitude);
  };

  const fn = () => {
    set_longitude(longitude => longitude - 0.00001);
  };

  const fn2 = () => {
    set_longitude(longitude => longitude + 0.00001);
  };

  const fn3 = () => {
    set_latitude(latitude => latitude + 0.00001);
  };

  const fn4 = () => {
    set_latitude(latitude => latitude - 0.00001);
  };

  const onSubmit = async () => {
    const arr = qtb(longitude, latitude);
    const uploadObj = {
      ...state,
      access_token: Taro.getStorageSync("access_token"),
      user_id: Taro.getStorageSync("user_id"),
      area_code: state.area_code,
      build_timestamp: state.build_timestamp
        ? Date.parse(new Date(state.build_timestamp)) / 1000
        : Math.ceil(new Date().getTime() / 1000)
    };
    if (files[0]) {
      Taro.uploadFile({
        url: baseUrl + "/append/project/add",
        filePath: files[0].url,
        name: "image_file",
        formData: {
          ...uploadObj
        },
        success(data) {
          const res = JSON.parse(data.data);
          if (res.res === 0) {
            getProjectAdjustApi({
              project_id: res.id,
              longitude: arr[0],
              latitude: arr[1]
            }).then(res2 => {
              if (res2.res === 0) {
                Taro.atMessage({
                  message: "新增成功",
                  type: "success"
                });
                Taro.navigateBack({
                  delta: 1
                });
              } else {
                Taro.atMessage({
                  message: res.msg,
                  type: "warning"
                });
              }
            });
          } else {
            Taro.atMessage({
              message: res.msg,
              type: "warning"
            });
          }
        }
      });
    } else {
      const res = await getProjectAddApi({
        ...uploadObj
      });
      if (res.res === 0) {
        getProjectAdjustApi({
          project_id: res.id,
          longitude: arr[0],
          latitude: arr[1]
        }).then(res2 => {
          if (res2.res === 0) {
            Taro.atMessage({
              message: "新增成功",
              type: "success"
            });
            Taro.navigateBack({
              delta: 1
            });
          } else {
            Taro.atMessage({
              message: res.msg,
              type: "warning"
            });
          }
        });
      }
    }
  };
  const changeSatellite = () => {
    dispatch({ type: "changeSatellite" });
  };
  return (
    <View className="lonlat">
      <View className="mapwrap">
        <Map
          longitude={center_longitude}
          latitude={center_latitude}
          style={{ width: "100%", height: 300 }}
          scale={10}
          markers={
            latitude
              ? [
                  {
                    longitude: longitude,
                    latitude: latitude
                  }
                ]
              : []
          }
          showScale={true}
          onTap={mapClick}
          enable-satellite={satellite}
        ></Map>
        {latitude && (
          <>
            <View className="controls item1" onClick={fn}>
              <Image
                src={require("../../../assets/images/left.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item2" onClick={fn2}>
              <Image
                src={require("../../../assets/images/right.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item3" onClick={fn3}>
              <Image
                src={require("../../../assets/images/top.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item4" onClick={fn4}>
              <Image
                src={require("../../../assets/images/bottom.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
          </>
        )}
      </View>
      <View className="button-wrap">
        <View className="button-item" onClick={changeSatellite}>
          {satellite ? "切换标准地图" : "切换卫星地图"}
        </View>
      </View>
      <AtForm>
        <AtInput
          required
          name="name"
          title="工程名称"
          type="text"
          placeholder="请输入工程名称"
          value={state.name}
          onChange={v => handleChange("name", v)}
        />

        <AtInput
          name="project_code"
          title="工程编码"
          type="text"
          placeholder="请输入工程编码，大写英文+数字"
          value={state.project_code}
          onChange={v => handleChange("project_code", v)}
        />

        <AtInput
          name="comment"
          title="工程描述"
          type="text"
          placeholder="请输入工程描述"
          value={state.comment}
          onChange={v => handleChange("comment", v)}
        />

        <Picker
          mode="multiSelector"
          range={state.selector}
          rangeKey="name"
          onColumnChange={columnChange}
        >
          <AtList className="bbb">
            <AtListItem
              extraText={state.select[2].name}
              title="所属区域"
            ></AtListItem>
          </AtList>
        </Picker>

        <AtInput
          name="address"
          title="工程地址"
          type="text"
          placeholder="请输入工程地址"
          value={state.address}
          onChange={v => handleChange("address", v)}
        />

        <AtInput
          name="building_area"
          title="建筑面积"
          type="text"
          placeholder="请输入建筑面积"
          value={state.building_area}
          onChange={v => handleChange("building_area", v)}
        />

        <AtInput
          name="building_number"
          title="幢数"
          type="text"
          placeholder="请输入幢数"
          value={state.building_number}
          onChange={v => handleChange("building_number", v)}
        />

        <AtInput
          name="constructor"
          title="建设单位"
          type="text"
          placeholder="请输入建设单位"
          value={state.constructor}
          onChange={v => handleChange("constructor", v)}
        />

        <AtInput
          name="constructor_user"
          title="建设单位联系人"
          type="text"
          placeholder="请输入建设单位联系人"
          value={state.constructor_user}
          onChange={v => handleChange("constructor_user", v)}
        />

        <AtInput
          name="constructor_phone"
          title="建设单位电话"
          type="text"
          placeholder="请输入建设单位电话"
          value={state.constructor_phone}
          onChange={v => handleChange("constructor_phone", v)}
        />

        <AtInput
          name="builder"
          title="施工单位"
          type="text"
          placeholder="请输入施工单位"
          value={state.builder}
          onChange={v => handleChange("builder", v)}
        />

        <AtInput
          name="builder_user"
          title="施工单位联系人"
          type="text"
          placeholder="请输入施工单位联系人"
          value={state.builder_user}
          onChange={v => handleChange("builder_user", v)}
        />

        <AtInput
          name="builder_phone"
          title="施工单位电话"
          type="text"
          placeholder="请输入施工单位电话"
          value={state.builder_phone}
          onChange={v => handleChange("builder_phone", v)}
        />

        <Picker mode="date" onChange={onDateChange}>
          <AtList>
            <AtListItem
              extraText={state.build_timestamp}
              title="请选择开工日期"
            ></AtListItem>
          </AtList>
        </Picker>

        <View
          className="at-input"
          style={{
            display: "flex",
            justifyContent: "space-between",
            width: "100%"
          }}
        >
          <Text>工程图片</Text>
          <AtImagePicker
            multiple={false}
            count={1}
            files={files}
            onChange={filesChange}
            name="image_file"
            length={1}
          />
        </View>

        <AtButton type="primary" onClick={onSubmit}>
          提交
        </AtButton>
      </AtForm>
      <AtMessage />
    </View>
  );
};

export default Index;
